package main

import (
	"fmt"
	"net"
	"net/http"
	"os"
	"os/signal"
	"syscall"
)

func main() {

	// TODO
	fmt.Println("[INFO] starting testing server")
	fmt.Println(os.Args)
	if len(os.Args)==1{
		return
	}
	
	ports:=os.Args[1:]
	for i, v := range ports {
		fmt.Printf("[INFO] start server %d, at port %s\n", i, v)
		newServer("0.0.0.0:" + v)
	}
	// //newServer("0.0.0.0:3000")
	// //newServer("0.0.0.0:6800")
	// newServer("0.0.0.0:8000")
	// newServer("0.0.0.0:8080")
	// newServer("0.0.0.0:8082")
	// newServer("0.0.0.0:9000")
	// newServer("0.0.0.0:10000")

	waitForSIG()
}

type server struct {
	host string
	l    net.Listener
}

func newServer(host string) {
	fmt.Println("[INFO] starting to listen : ", host)
	l, _ := net.Listen("tcp", host)
	s := &server{
		host,
		l,
	}
	go http.Serve(s.l, s)
}

func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// str := fmt.Sprint("method=", r.Method, " host=", r.Host, "  path=", r.URL.Path)
	// fmt.Println(str)
	now := getNow()
	formattedTime := now.Format("2006-01-02 15:04:05")
	str := fmt.Sprint(formattedTime," [info] ",r.RemoteAddr," method=", r.Method, " host=", r.Host, "  path=", r.URL.Path)
	fmt.Println(str)
	if strings.HasSuffix(r.URL.Path, ".mp4") {
		w.Header().Add("Content-Type", "video/mp4")
	}
	w.Write([]byte("hello, " + str))
}

func waitForSIG() {
	sigCh := make(chan os.Signal, 1)
	signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
	s := <-sigCh
	fmt.Printf("[I] signal:%s, Server is going to be closed\n", s.String())
}
